package com.qingmu.club.minaapi.controller.member;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qingmu.club.minaapi.model.QueryLearnDiaryModel;
import com.qingmu.club.minaapi.model.QueryUserCourseModel;
import com.qingmu.club.minaapi.plus.entity.*;
import com.qingmu.club.minaapi.custom.logic.LearnDiaryLogic;
import com.qingmu.club.minaapi.plus.service.*;
import com.qingmu.club.minaapi.utils.KeyValueDefine;
import com.qingmu.club.minaapi.utils.ResponseObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 日学习记主表 前端控制器
 * </p>
 *
 * @author duke
 * @since 2019-08-20
 */
@RestController
@CrossOrigin(origins = "*", methods = {RequestMethod.POST, RequestMethod.GET})
@Api(value = "学习日记(会员端小程序)", description = "学习日记(会员端小程序)")
@RequestMapping("/member/learnDiary")
public class MemberLearnDiaryController {

    @Autowired
    LearnDiaryService learnDiaryService;

    @Autowired
    LearnDiaryReplyService learnDiaryReplyService;

    @Autowired
    ClubUsersService clubUsersService;

    @Autowired
    ClubShopService clubShopService;

    @Autowired
    UsersService usersService;

    @Autowired
    ClubUsersCourseService clubUsersCourseService;

    @Autowired
    ClubUsersClasshoursService clubUsersClasshoursService;

    @Autowired
    CourseService courseService;

    @RequestMapping(value = "/queryMemberClassHours", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "查询会员剩余课时")
    public ResponseEntity queryMemberClassHours(
            @ApiParam(required = true, value = "用户id") @RequestParam(required = true) String userId,
            @ApiParam(required = true, value = "门店id") @RequestParam(required = true) String shopId
    ) {
        Users users = this.usersService.getById(userId);
        if (users == null) {
            return ResponseObject.error(401, "用户信息找不到");
        }

        QueryWrapper<ClubUsers> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(ClubUsers.USER_ID, userId).eq(ClubUsers.SHOP_ID, shopId);
        ClubUsers clubUsers = this.clubUsersService.getOne(queryWrapper);
        if (clubUsers == null) {
            return ResponseObject.error(558, "请先关注门店");
        }

        Course course = this.courseService.getById(clubUsers.getBuyCourseId());
        String courseName="";
        if(course!=null){
            courseName = course.getCourseName();
        }

//        //课程
//        QueryWrapper<ClubUsersCourse> onlineCourse = new QueryWrapper<>();
//        onlineCourse.lambda().eq(ClubUsersCourse::getClubUsersId, clubUsers.getId()).eq(ClubUsersCourse::getType, 0);
//        ClubUsersCourse clubUsersCourse = this.clubUsersCourseService.getOne(onlineCourse);
//        if(clubUsersCourse==null){
//            return ResponseObject.success();
//        }
//
//        QueryWrapper<ClubUsersClasshours> qw = new QueryWrapper<>();
//        qw.lambda()
//                .eq(ClubUsersClasshours::getClubUsersId, clubUsers.getId())
//                .eq(ClubUsersClasshours::getCourseId, clubUsersCourse.getCourseId());
//        List<ClubUsersClasshours> clubUsersClasshoursList = this.clubUsersClasshoursService.list(qw);
//
//        QueryUserCourseModel userCourseModel = new QueryUserCourseModel();
//        BeanUtils.copyProperties(clubUsersCourse, userCourseModel);
//        userCourseModel.setClubUsersClasshoursList(clubUsersClasshoursList);

        QueryWrapper<ClubUsersClasshours> qw = new QueryWrapper<>();
        qw.lambda().eq(ClubUsersClasshours::getClubUsersId,clubUsers.getId()).eq(ClubUsersClasshours::getStatus,0).eq(ClubUsersClasshours::getCourseId,clubUsers.getBuyCourseId());
        List<ClubUsersClasshours> noFinishLearnList = this.clubUsersClasshoursService.list(qw);

        QueryWrapper<ClubUsersClasshours> qws = new QueryWrapper<>();
        qws.lambda().eq(ClubUsersClasshours::getClubUsersId,clubUsers.getId()).eq(ClubUsersClasshours::getStatus,1).eq(ClubUsersClasshours::getCourseId,clubUsers.getBuyCourseId());
        List<ClubUsersClasshours> finishLearnList = this.clubUsersClasshoursService.list(qws);

        HashMap<String,Object> map = new HashMap<>();
        map.put("courseName",courseName);
        map.put("attendShopName",clubUsers.getAttendShopName());
        map.put("sumHours",noFinishLearnList.size()+finishLearnList.size());
        map.put("residueHours",noFinishLearnList.size());
        map.put("noFinishLearnList",noFinishLearnList);
        map.put("finishLearnList",finishLearnList);
        return ResponseObject.success(map);

    }


    @RequestMapping(value = "/query", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "查询学习日记")
    public ResponseEntity query(
            @ApiParam(required = true, value = "用户id") @RequestParam(required = true) String userId,
            @ApiParam(required = true, value = "门店id") @RequestParam(required = true) String shopId,
            @ApiParam(required = false, value = "当前页",example = "1") @RequestParam(required = false) Integer page,
            @ApiParam(required = false, value = "每页数量",example = "10") @RequestParam(required = false) Integer pageSize

    ) {

        Users users = this.usersService.getById(userId);
        if(users==null){
            return ResponseObject.error(401,"用户信息找不到");
        }

        QueryWrapper<ClubUsers> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(ClubUsers.USER_ID,userId).eq(ClubUsers.SHOP_ID,shopId);
        ClubUsers clubUsers = this.clubUsersService.getOne(queryWrapper);
        if(clubUsers==null){
            return ResponseObject.error(558,"请先关注门店");
        }

        ClubShop clubShop = this.clubShopService.getById(shopId);
        if(clubShop==null){
            return ResponseObject.error(601,"门店不存在");
        }
        String key  = KeyValueDefine.LATENT;
        Boolean value  = false;
        if(clubUsers.getUserShowStatus().equals(key)){//潜在学员不给发日志
            value=true;
        }

        if(page==null){
            page=0;
        }
        if(pageSize==null){
            pageSize=10;
        }

        QueryWrapper<LearnDiary> qw = new QueryWrapper<>();
        //qw.eq(LearnDiary.SHOP_ID,shopId).eq(LearnDiary.USER_ID,clubUsers.getId()).orderByDesc(LearnDiary.CREATE_TIME);
        qw.eq(LearnDiary.USER_ID,clubUsers.getId()).orderByDesc(LearnDiary.CREATE_TIME);
        IPage<LearnDiary> iPage = learnDiaryService.page(new Page<>(page,pageSize),qw);
        List<LearnDiary> learnDiaryList = iPage.getRecords();

        List<QueryLearnDiaryModel> results = new ArrayList();
        for(LearnDiary learnDiary :learnDiaryList){
            QueryLearnDiaryModel item = new QueryLearnDiaryModel();
            BeanUtils.copyProperties(learnDiary, item);

            QueryWrapper<LearnDiaryReply> lrdFrist = new QueryWrapper<>();
            lrdFrist.eq(LearnDiaryReply.LEARN_DIARY_ID,learnDiary.getId());
            List<LearnDiaryReply> replyList = this.learnDiaryReplyService.list(lrdFrist);
            item.setReplyList(replyList);

            results.add(item);
        }

        return ResponseObject.successIpageDate(iPage,results,key,value);
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "会员发布学习日记")
    public ResponseEntity add(
            @ApiParam(required = true, value = "作者id") @RequestParam(required = true) String userId,
            @ApiParam(required = true, value = "门店id") @RequestParam(required = true) String shopId,
            @ApiParam(required = false, value = "日记内容") @RequestParam(required = false) String content,
            @ApiParam(required = false, value = "图片") @RequestParam(required = false) String imageUrl,
            @ApiParam(required = false, value = "视频") @RequestParam(required = false) String videoUrl
    ) {
        Users users = this.usersService.getById(userId);
        if(users==null){
            return ResponseObject.error(401,"会员信息找不到");
        }

        QueryWrapper<ClubUsers> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(ClubUsers.USER_ID,userId).eq(ClubUsers.SHOP_ID,shopId);
        ClubUsers clubUsers = this.clubUsersService.getOne(queryWrapper);
        if(clubUsers==null){
            return ResponseObject.error(558,"会员信息找不到");
        }

        if(clubUsers.getUserShowStatus().equals(KeyValueDefine.LATENT)){
            return ResponseObject.error(601,"该功能权限暂未开发，请购买课程");
        }

        ClubShop clubShop =this.clubShopService.getById(shopId);
        if(clubShop==null){
            return ResponseObject.error(601,"门店信息找不到");
        }

        if(StringUtils.isEmpty(content) && StringUtils.isEmpty(imageUrl) && StringUtils.isEmpty(videoUrl)){
            return ResponseObject.error(552,"请输入内容");
        }

        LearnDiary ld = new LearnDiary();
        ld.setAuthorId(clubUsers.getId());
        ld.setContent(content);
        ld.setImageUrl(imageUrl);
        ld.setVideoUrl(videoUrl);
        ld.setAuthorName(users.getUserName());
        ld.setAuthorIcon(users.getUserIcon());
        ld.setAuthorType(1);//会员
        ld.setShopId(shopId);
        ld.setUserId(clubUsers.getId());
        ld.setDiaryTime(new Date());
        ld.setStatus(1);

        boolean state = this.learnDiaryService.save(ld);
        if(!state){
            return ResponseObject.error(503,"发布失败");
        }
        return ResponseObject.success();
    }

    @RequestMapping(value = "/removeById", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "删除日记")
    public ResponseEntity removeById(
            @ApiParam(required = true, value = "日记id") @RequestParam(required = true) String learnDiaryId
    ) {

        LearnDiary learnDiary = learnDiaryService.getById(learnDiaryId);

        if(learnDiary==null){
            return ResponseObject.error(601,"日记信息找不到");
        }
        boolean state = learnDiaryService.removeById(learnDiaryId);
        if(!state){
            return ResponseObject.error(503,"删除失败");
        }
        return ResponseObject.success();
    }


    @RequestMapping(value = "/commentDiary", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "评论日记")
    public ResponseEntity commentDiary(
            @ApiParam(required = true, value = "评论人id") @RequestParam(required = true) String userId,
            @ApiParam(required = true, value = "日记id") @RequestParam(required = true) String id,
            @ApiParam(required = true, value = "评论内容") @RequestParam(required = true) String content
    ) {
        Users users = this.usersService.getById(userId);
        if(users==null){
            return ResponseObject.error(401,"会员信息找不到");
        }

        LearnDiary learnDiary = learnDiaryService.getById(id);
        if(learnDiary==null){
            return ResponseObject.error(601,"日记信息找不到");
        }

        LearnDiaryReply ldr = new LearnDiaryReply();
        ldr.setLearnDiaryId(id);

        ldr.setReplierId(userId);
        ldr.setReplierContent(content);
        ldr.setReplierIcon(users.getUserIcon());
        ldr.setReplierName(users.getUserName());
        ldr.setStatus(KeyValueDefine.ONLINE_STATUS);

        boolean state = learnDiaryReplyService.save(ldr);
        if(!state){
            return ResponseObject.error();
        }
        return ResponseObject.success();
    }


    @RequestMapping(value = "/replyComment", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "回复评论")
    public ResponseEntity replyComment(
            @ApiParam(required = true, value = "回复人id") @RequestParam(required = true) String userId,
            @ApiParam(required = true, value = "评论id") @RequestParam(required = true) String replyId,
            @ApiParam(required = true, value = "回复内容") @RequestParam(required = true) String content
    ) {


        Users users = this.usersService.getById(userId);
        if(users==null){
            return ResponseObject.error(401,"会员信息找不到");
        }

//        QueryWrapper<ClubUsers> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq(ClubUsers.USER_ID,userId).eq(ClubUsers.SHOP_ID,shopId);
//        ClubUsers clubUsers = this.clubUsersService.getOne(queryWrapper);
//        if(clubUsers==null){
//            return ResponseObject.error(558,"会员信息找不到");
//        }

        LearnDiaryReply learnDiaryReply = learnDiaryReplyService.getById(replyId);
        if (learnDiaryReply == null) {
            return ResponseObject.error(601, "评论信息找不到");
        }


        LearnDiaryReply ldr = new LearnDiaryReply();

        ldr.setByReply(learnDiaryReply.getReplierName());
        ldr.setByReplyId(learnDiaryReply.getReplierId());
        ldr.setLearnDiaryId(learnDiaryReply.getLearnDiaryId());
        ldr.setParentId(replyId); //父级

        ldr.setReplierId(userId);
        ldr.setReplierContent(content);
        ldr.setReplierIcon(users.getUserIcon());
        ldr.setReplierName(users.getUserName());
        ldr.setStatus(KeyValueDefine.ONLINE_STATUS);

        boolean state = learnDiaryReplyService.save(ldr);
        if (!state) {
            return ResponseObject.error();
        }
        return ResponseObject.success();
    }


    @RequestMapping(value = "/removeReplyById", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "删除回复")
    public ResponseEntity removeReplyById(
            @ApiParam(required = true, value = "回复id") @RequestParam(required = true) String replyId
    ) {

        LearnDiaryReply learnDiaryReply = learnDiaryReplyService.getById(replyId);

        if(learnDiaryReply==null){
            return ResponseObject.error(601,"日记信息找不到");
        }
        boolean state = learnDiaryReplyService.removeById(replyId);
        if(!state){
            return ResponseObject.error(503,"删除失败");
        }
        return ResponseObject.success();
    }


}

